"""
ROMA 资源池管理 API 路由
"""
import os
import httpx
import json
import httpx
import os
from datetime import datetime, timedelta

from fastapi import APIRouter, HTTPException
from schemas.roma_pool_schema import RomaPoolListResponse

CACHED_TOKEN_PATH = "cached_roma_token.token"
TOKEN_EXPIRE_DELTA = timedelta(hours=23, minutes=50)

router = APIRouter(prefix="/api/roma-pools", tags=["ROMA资源池管理"])

@router.get("", response_model=RomaPoolListResponse, summary="获取ROMA资源池列表")
async def get_roma_pools():
    """
    从华为云 ROMA 平台获取资源池列表

    - 调用外部 API 获取资源池信息
    - 无需认证
    - 返回完整的资源池列表
    """
    # 从环境变量获取 csb_token
    csb_token = os.getenv("CSB_TOKEN")
    print("csb_token:", csb_token)
    if not csb_token:
        raise HTTPException(
            status_code=500,
            detail="CSB_TOKEN 环境变量未配置"
        )

    url = "https://csb.roma.huawei.com/csb/rest/saas/ei/eiWizard/train/pools/list"

    token_to_use = reuse_or_fetch_token(
        account_name="BMC_API_USER",
        account_secret="AESGCM:2856B514BE721213DBEADA0A5F37BD15:57AA692302F16DE42F5914D82F45B8F94EA1635A9D72912911C19BD748F63CD6E33C34BDB2AFD98DDF67A45F1A084DF2E7DED0C3",
    )

    headers = {
        "Content-Type": "application/json",
        "Authorization": token_to_use,
        "csb_token": csb_token,
    }
    query_params = {
        "appid": "com.app.bmc.ai.aicase"
    }

    try:
        async with httpx.AsyncClient(verify=False) as client:
            response = await client.get(url, headers=headers, params=query_params, timeout=30.0)
            response.raise_for_status()
            data = response.json()
            return data
    except httpx.HTTPStatusError as e:
        raise HTTPException(
            status_code=e.response.status_code,
            detail=f"ROMA API 请求失败: {e.response.text}"
        )
    except httpx.RequestError as e:
        raise HTTPException(
            status_code=500,
            detail=f"ROMA API 请求异常: {str(e)}"
        )
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"获取资源池列表失败: {str(e)}"
        )


def reuse_or_fetch_token(account_name, account_secret):
    """
    Return cached token if not expired, else fetch a new one and cache with timestamp.
    """
    now = datetime.now(datetime.now().tzinfo)
    print("Now is ", now)
    # Check for existing cached token
    if os.path.exists(CACHED_TOKEN_PATH):
        with open(CACHED_TOKEN_PATH, "r", encoding="utf-8") as f:
            try:
                cached = json.load(f)
                ts = cached.get("timestamp")
                if ts:
                    ts_dt = datetime.fromisoformat(ts)
                    if now - ts_dt < TOKEN_EXPIRE_DELTA and "access_token" in cached:
                        print("✅ Using cached token.")
                        return cached["access_token"]
            except Exception as e:
                print(f"⚠️ Failed to load cached token: {e}")

    # Fetch new token
    url = "https://csb.roma.huawei.com/csb/v2/enterprise/tenant/rest/csbiam/auth/enterprise-token"
    headers = {"Content-Type": "application/json"}
    data = {
        "data": {
            "type": "JWT-Token",
            "attributes": {
                "integrationAccountName": account_name,
                "integrationAccountSecret": account_secret,
            },
        }
    }
    with httpx.Client(proxy=None, verify=False) as client:
        response = client.post(url, headers=headers, json=data)
        response.raise_for_status()
        access_token = response.json()
        # Cache with timestamp
        with open(CACHED_TOKEN_PATH, "w", encoding="utf-8") as f:
            cache_content = {
                "timestamp": now.isoformat(),
                "access_token": access_token["accessToken"],
            }
            json.dump(cache_content, f, ensure_ascii=False)
            f.write("\n")
        print("✅ Cached new token to", CACHED_TOKEN_PATH)
        return access_token['accessToken']
